package com.donger.common.sso.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.extra.spring.SpringUtil;
import com.donger.common.core.utils.Result;
import com.donger.common.sso.entity.UserInfo;
import com.donger.common.sso.feign.SsoUserFeign;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author pmc
 * <p>
 * 用户相关工具类
 */
@Slf4j
public class AuthUtils {


    private static final Map<String, Object> CACHE_MAP = Dict.create();


    /**
     * 获取登陆用户id
     *
     * @return
     */
    public static Long getUserId() {
        return StpUtil.getLoginIdAsLong();
    }

    /**
     * 获取用户信息
     * 获取远程用户中心用户信息，
     * 然后根据用户id 进行缓存
     * 缓存信息 10分钟自动失效
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        Long userId = getUserId();
        if (CACHE_MAP.containsKey(String.valueOf(userId))) {
            return (UserInfo) CACHE_MAP.get(String.valueOf(userId));
        } else {
            SsoUserFeign ssoUserFeign = SpringUtil.getBean(SsoUserFeign.class);
            Result<UserInfo> userInfo = ssoUserFeign.getUserInfo(userId);
            UserInfo data = userInfo.getData();
            CACHE_MAP.put(String.valueOf(userId), data);
            return data;
        }
    }


}
